package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.CommentMapper;
import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo")
public class WeiboController {

    @Autowired
    WeiboMapper mapper;

    @RequestMapping("/insert")
    public int insert(@RequestBody WeiboDto weiboDto, HttpSession session){
        UserVO userVO = (UserVO)session.getAttribute("user");
        if(userVO==null){
            return 2;//未登录
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDto,weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());

        return mapper.insert(weibo);
    }

    @RequestMapping("/select")
    public List<WeiBoIndexVo> select(){
        return mapper.select();
    }

    @RequestMapping("/selectById")
    public WeiboDetailVo selectById(int id){
        return mapper.selectById(id);
    }

    @RequestMapping("/select/mine")
    public ResultVo selectMine(HttpSession session){
        UserVO user = (UserVO) session.getAttribute("user");
        if(user==null){
            return new ResultVo(2,"用户未登录",null);
        }
        System.out.println(new ResultVo(2,"用户未登录",null));
        return new ResultVo(1,"请求成功",mapper.selectMine(user.getId()));
    }

    @Autowired
    CommentMapper commentMapper;
    @RequestMapping("/delete")
    public int delete(int id,HttpSession session){
        UserVO user = (UserVO) session.getAttribute("user");
        if(user==null){
            return 2;
        }
        mapper.deleteById(id);
        commentMapper.deleteByWeiboId(id);
        return 1;
    }
}
